package com.whut.www.file_storage;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by clvc on 2017/7/7.
 * 真正的速度是看不见的 !
 * Today is today , we will go !
 */

public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
    public CustomSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory
            factory, int version) {
        super(context, name, factory, version);
    }

    /**
     * 在数据库中创建表
     * app第一次安装并且首次初始化CustomSQLiteOpenHelper获取SQLiteDatabase时才会调用
     * 随后更改数据库的名称,此后第一次初始化CustomSQLiteOpenHelper获取SQLiteDatabase时也会调用
     *
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i("CustomSQLiteOpenHelper", "---onCreate()--->" + "创建数据库");
        db.execSQL("create table if not exists tb_words(_id integer primary key autoincrement ,word varchar(20),detail varchar(20))");
        db.execSQL("create table if not exists tb_newWords(_id integer primary key autoincrement ,word varchar(20),detail varchar(20))");
    }

    /**
     * version变化且首次初始化才会调用
     *
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("CustomSQLiteOpenHelper", "---onUpgrade()--->" + "检查数据库升级");
        if (newVersion > oldVersion) {
            Log.i("CustomSQLiteOpenHelper", "---onUpgrade()--->" + "数据库升级了");
            db.execSQL("alter table tb_words add author varchar(20)");
        }
    }

    /**
     * 将cursor中的数据转存到List中
     * 查询数据后cursor的游标停留在-1的位置,此时取值会抛出异常,应先通过cursor.moveToNext()移动游标在进行取值
     *
     * @param cursor
     * @return
     */
    public ArrayList<HashMap<String, String>> cursorToList(Cursor cursor) {
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        //获得cursor中的数据的总数
        int count = cursor.getCount();
        while (cursor.moveToNext()) {
            HashMap<String, String> map = new HashMap<>();
            //获取列的数量
            int columnCount = cursor.getColumnCount();
            for (int j = 0; j < columnCount; j++) {
                //获取列名
                String columnName = cursor.getColumnName(j);
                //通过列名获取列的下标
                int columnIndex = cursor.getColumnIndex(columnName);
                //通过下标获取数据
                String data = cursor.getString(j);
                map.put(columnName, data);
            }
            list.add(map);
        }
        //关闭资源
        cursor.close();
        return list;
    }
}
